# If successfully connect to the host where your repo is located,
# then push your repo to the remote.
# 
# Requirements:
#   - You need Git installed before you run this script
#   - I use SyncToy to sync the config folders (try any tools you like)
# 
# How to use:
#   - Put this script into you repo's root directory,
#   - run this script in PowerShell with command `./sync-push.ps1`.
#   - Or schedule it with Windows Task Scheduler.

$HostName="gitee.com"
$Port=443
$SyncToy="C:\Program Files\SyncToy 2.1\SyncToyCmd.exe"
$LogPath = "./sync-push.log"

if (-not (Test-Path $LogPath)){
    New-Item -ItemType File -Path $LogPath -Force
}

if (-not (Test-Path $SyncToy)){
    [string]$(Get-Date) + " SyncToy is not existed" | Out-File -FilePath $LogPath -Append
    [string]$(Get-Date) + " Fail to sync!" | Out-File -FilePath $LogPath -Append
    "" | Out-File -FilePath $LogPath -Append
    
    notepad $LogPath
    pause
    exit 0
}

if (Test-NetConnection -ComputerName $HostName -Port $Port){
    # pull the latest files on the remote first
    [string]$(Get-Date) + " git pull" | Out-File -FilePath $LogPath -Append
    $(git pull) | Out-File -FilePath $LogPath -Append
    "" | Out-File -FilePath $LogPath -Append

    [string]$(Get-Date) + " Run SyncToy" | Out-File -FilePath $LogPath -Append
    & $SyncToy -R | Out-File -FilePath $LogPath -Append
    "" | Out-File -FilePath $LogPath -Append

    [string]$(Get-Date) + " Ready to push" | Out-File -FilePath $LogPath -Append
    "" | Out-File -FilePath $LogPath -Append
    
    [string]$(Get-Date) + " git status" | Out-File -FilePath $LogPath -Append
    $(git status) | Out-File -FilePath $LogPath -Append
    "" | Out-File -FilePath $LogPath -Append

    [string]$(Get-Date) + " git add ." | Out-File -FilePath $LogPath -Append
    $(git add .) | Out-File -FilePath $LogPath -Append
    "" | Out-File -FilePath $LogPath -Append

    [string]$(Get-Date) + " git commit -m 'Sync Push'" | Out-File -FilePath $LogPath -Append
    $(git commit -m 'Sync Push') | Out-File -FilePath $LogPath -Append
    "" | Out-File -FilePath $LogPath -Append

    [string]$(Get-Date) + " git push" | Out-File -FilePath $LogPath -Append
    $(git push) | Out-File -FilePath $LogPath -Append
    "" | Out-File -FilePath $LogPath -Append

    [string]$(Get-Date) + " Complete!" | Out-File -FilePath $LogPath -Append
    "" | Out-File -FilePath $LogPath -Append

    notepad $LogPath
    pause
    exit 0
}
else {
    [string]$(Get-Date) + " Cannot connect to $HostName through port $Port" | Out-File -FilePath $LogPath -Append
    [string]$(Get-Date) + " Fail to push!" | Out-File -FilePath $LogPath -Append
    "" | Out-File -FilePath $LogPath -Append
    
    notepad $LogPath
    pause
    exit 0
}